<template>
    <el-container>
        <el-main class="login-main">
            <div class="login-box">
                <el-form
                        :model="loginUser"
                        :rules="rules"
                        :status-icon="true"
                        ref="loginForm"
                        :label-position="'top'"
                        :hide-required-asterisk="true"
                        class="login-form"
                        label-width="0"
                        id="loginForm"
                        action="/api/signin"
                        method="post"
                        enctype="multipart/form-data"
                        @submit.native.prevent
                        @submit.prevent="submitForm"
                >
                    <el-form-item
                            class="info-line login-name"
                            prop="username"
                    >
                        <el-input
                                v-model="loginUser.username"
                                placeholder="请输入用户名"
                                name="username"
                                autofocus
                                ref="inputs"
                        ></el-input>

                        <i class="login-inp-icon"></i>
                    </el-form-item>
                    <el-form-item
                            class="info-line login-pass"
                            prop="password"
                    >
                        <el-input
                                v-model="loginUser.password"
                                placeholder="请输入密码"
                                type="password"
                                id="password"
                                onpaste="return false"
                                onselectstart="return false"
                                name="password"
                        ></el-input>
                        <i class="login-inp-icon-pwd"></i>
                    </el-form-item>
                    <el-form-item>
                        <div class="loading-img"></div>
                        <input
                                type="submit"
                                value="登录"
                                @click="submitForm"
                                class="login-btn"
                        />
                        <div class="hover-img"></div>
                    </el-form-item>
                    <p class="copy-info">©拓尔思天行网安信息技术有限责任公司</p>
                </el-form>
            </div>
        </el-main>
    </el-container>
</template>

<script>
import Rules from '@/util/customRules'
// import {getdbDriverId,getFiletype} from '../../util/dictionaryCode'
// import $ from 'jquery'
import md5 from 'js-md5'

import Menu from '@/data/menu'

export default {
  data() {
    var checkVerify = (rule, value, callback) => {
      // callback();//临时去除验证
      if (value === '') {
        callback(new Error('验证码不能为空'));
      } else {
        this.$api.checkVerify({ code: value })
          .then(res => {
            if (res.data.code === 200) {
              callback();
            } else {
              this.getCaptcha();
              callback(new Error('验证码错误！'));
            }
          });
      }
    };

    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.newpassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };

    return {
      certificate: true,
      isIe: false,
      Rtitles: '',
      editID: '',
      dialogVisible: false,
      imgSrc: '',
      disable: false,
      loading: false,
      originalpw: '',
      loginUser: {
        username: '',
        password: '',
        code: '',
        Filedata: '',
        filename: ''
      },
      form: {
        password: '',
        newpassword: '',
        repassword: ''
      },
      rules2: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            validator: ((rule, value, callback) => {
              if (value === '') {
                callback();
              } else if (value.length >= 8 && value.length <= 32) {
                Rules.validateloginPass(rule, value, function(error) {
                  if (error) {
                    callback(error);
                  } else {
                    callback();
                  }
                })
              } else {
                callback(new Error('请输入8-32个字符'));
              }

            }),
            trigger: 'blur'
          }
        ],
        newpassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            validator: ((rule, value, callback) => {
              if (value === '') {
                callback();
              } else if (value.length >= 8 && value.length <= 32) {
                Rules.validateloginPass(rule, value, function(error) {
                  if (error) {
                    callback(error);
                  } else {
                    callback();
                  }
                })
              } else {
                callback(new Error('请输入8-32个字符'));
              }

            }),
            trigger: 'blur'
          },
          { validator: (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请输入新密码'));
            } else if (value == this.form.password) {
              callback(new Error('新密码与旧密码不能一致!'));
            } else {
              callback();
            }
          }, trigger: 'blur' }
        ],
        repassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ],
      },
      rules: {
        username: [
          {
            required: true,
            message: '账号不能为空',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空',
            trigger: 'blur'
          },
          {
            validator: checkVerify,
            trigger: 'blur'
          }
        ],
      }
    };
  },
  computed: {
    home() {
      return '/'+this.$store.getters.getGlobalTheme;
    }
  },
  methods: {
    // 登录按钮事件
    submitForm() {
      var me =this;
      this.disable = true;
      this.loading = true;
      this.$refs['loginForm'].validate(valid => {
        if (valid) {
          // if (this.isIe) {
          //   $('#loginForm').find('#password').val((this.loginUser.password));
          //   $('#loginForm').ajaxSubmit({
          //     type: 'post',
          //     dataType: 'text',
          //     enctype: 'multipart/form-data',
          //     timeout: 6000,
          //     success: (result) => {
          //       $('#loginForm').find('#password').val(this.loginUser.password);
          //       this.loading = false;
          //       this.disable = false;
          //
          //       const res = JSON.parse(result);
          //       this.userId = res.userId;
          //       if (res.code === 200) {
          //         me.loginSuc(res);
          //
          //       } else if (res.code === 603) {
          //         me.loginSuc(res);
          //       // 603未授权
          //       // me.golicense(res);
          //       // me.$notify({
          //       //   title: '错误',
          //       //   type: 'error',
          //       //   message: '账号未授权',
          //       //   position: 'top-right',
          //       //   duration: 2000,
          //       //   onClose: () => {
          //       //     me.disable = false;
          //       //     me.loading = false;
          //       //   }
          //       // });
          //       } else if (res.code === 601) {
          //       // 601密码过期修改密码
          //         me.$notify({
          //           title: '警告',
          //           type: 'warning',
          //           message: res.msg,
          //           position: 'top-right',
          //           duration: 1000,
          //           onClose: () => {
          //             me.showDiog(res.userId, res.name);
          //           }
          //         });
          //       } else {
          //         me.getCaptcha();
          //         me.$notify({
          //           title: '错误',
          //           type: 'error',
          //           message: res.msg,
          //           position: 'top-right',
          //           duration: 2000,
          //           onClose: () => {
          //             me.disable = false;
          //             me.loading = false;
          //           }
          //         });
          //       }
          //     }
          //   });
          // } else {
          //   this.$api.login({
          //     userName: this.loginUser.username,
          //     passWord: this.loginUser.password
          //   }).then((res) => {
          //     if (res.data.code === 200) {
          // this.$store.dispatch('sessionStorageUser', res.data.data)
          this.$store.dispatch('sessionStorageUser', {
            name: '系统管理员',
            id: 1
          })
          this.$store.dispatch('initMenuData', Menu);
          this.$router.push({
            path: this.home
          })
          // } else {
          //   this.$message({
          //     type: 'error',
          //     message: res.data.message
          //   })
          // }
          // }).catch((err) => {
          //
          // })
          // }
        } else {
          this.getCaptcha();
          this.disable = false;
          this.loading = false;
        }
      });
    },

    // 修改密码保存
    mySubmit() {
      const me = this;
      (this.$refs['editorForm']).validate(valid => {
        if (valid) {
          this.$api.head.resetPwdNotLogin({
            pwdOld: (this.form.password),
            id: this.editID,
            pwdNew: (this.form.newpassword)
          })
            .then((res) => {
              if (res.data.code == 200) {
                me.dialogVisible = false;
                me.$message({
                  type: 'success',
                  message: res.data.data,
                  center: true
                });
              } else {
                me.$message({
                  type: 'error',
                  message: res.data.message,
                  center: true
                });
              }
            })
            .catch((err) => {});
        }
      });
    },
    // 正常登录
    loginSuc(res) {
      JsCookie.set('LoginUser', {
        name: this.loginUser.username,
        id: res.code == '200'?res.userId:-1
      });
      try {
        this.$store.commit('setInitData', { menu: res.menus[0].children, userid: res.userId, name: this.loginUser.username });
      } catch (e) {
        console.error(e)

      }
      this.$store.dispatch('saveMenuData', res.menus[0].children).then(() => {
      });
      if (res.code == 200) {
        this.$notify({
          title: '成功',
          message: '登录成功',
          type: res.code == '200'?'success':'error',
          position: 'top-right',
          duration: 400,
          onClose: () => {
            window.location.href = '/'
          }
        });
      } else {
        window.location.href = '/'
      }
      if (res.msg && res.msg!='登录成功'  && res.code != 603) {
        JsCookie.set('message', res.msg)
      }

    },
    // 密码过期弹窗
    showDiog(id, name) {
      this.dialogVisible = true;
      this.editID = id;
    },
    // 上传文件判断
    changeFile(e) {
      if (e.target.value) {
        if (e.target.value.slice(-7) !== '.topkey') {
          this.$notify({
            type: 'warning',
            title: '警告',
            message: '上传文件只能是topkey格式文件',
            position: 'top-right',
            duration: 1000
          });
          return false;
        }
        if (this.isIe) {
          this.loginUser.filename = e.target.value.substring(e.target.value.lastIndexOf('/') + 1);
        } else {
          if (e.target.files[0].size.toFixed(2) >= 5 *  1024) {
            this.$message({
              message: '请上传小于5k的证书',
              type: 'error',
              center: true
            });
            $('#upload')[0]?$('#upload')[0].value = '':'';
            return false;
          }
          this.loginUser.Filedata = e.target.files[0];
          this.loginUser.filename = e.target.value.substring(e.target.value.lastIndexOf('/') + 1);
        }

      }
    },
    getCaptcha() {
      if (this.isIe) {

        this.imgSrc = '/api/getVerify?'+Math.random();
      } else {
        this.$api.getCaptcha(Math.random()).then((response) => {
          let reader = new FileReader();
          reader.onload = (e) => {
            this.imgSrc = e.target.result
          };
          reader.readAsDataURL(response.data)
        }).catch(e => {});
      }

    },
    // 获取标题
    async getTitle() {
      return await this.$api.getTitle().then(res => {
        if (res.data.code == 200) {
          this.Rtitles = res.data.data;
          document.title = res.data.data;
          this.$store.dispatch('updateTitle', res.data.data)
          JsCookie.set('headerTitle', res.data.data);
        }
      }).catch(e => {});
    }
  },
  created() {
    if (
      navigator.appName == 'Microsoft Internet Explorer' &&
      navigator.appVersion.split(';')[1].replace(/[ ]/g, '') == 'MSIE9.0'
    ) {
      this.isIe = true;
    }
  //  Promise.all([ this.getTitle()]).then(() =>{
  //    this.getCaptcha();
  //  })
  },

  async mounted() {
    // this.getCaptcha();
  }
}
</script>

<style scoped lang="less">
    .login-main {
        position: relative;
        width: 100%;
        height: 100%;
        font-size: 14px;
        background: url(~@/assets/login/mobile-bg1.png) no-repeat center center;
        background-size: 100% 100%;
    }
    .login-main{
        display: table;
    }
    .login-form {
        width: 80%;
        margin: 0 auto;
    }
    .login-box {
        display: table-cell;
        vertical-align: middle;
    }


    .login-btn {
        width: 100%;
        height: 61px;
        font-size: 15px;
        border: none;
        cursor: pointer;
         background: url(~@/assets/login/login_btn.png) no-repeat center center;
        color: #edfbfe;
        text-align: center;
        margin-top: 35px;
        padding-bottom: 5px;
    }

    .login-btn:focus {
        outline: 0;
    }

    .login-btn:hover {
        width: 100%;
        height: 61px;
        font-size: 15px;
        border: none;
        cursor: pointer;
         background: url(~@/assets/login/login_abtn.png) no-repeat center center;
        color: #edfbfe;
        text-align: center;
        margin-top: 35px;
        padding-bottom: 5px;
    }
    .hover-img{
      width: 0px;
      height: 0px;
      overflow: hidden;
       background: url(~@/assets/login/login_abtn.png) no-repeat center center;
    }
    .loading-img {
         background: url(~@/assets/login/login_abtn.png) no-repeat center center;
        display: none;
    }

    .info-line {
    }

    .copy-info {
        text-align: center;
        margin-top: 55px;
        color: #ffffff;
        font-size: 12px;
    }

    .login-name,
    .login-pass {
        position: relative;
    }

    .login-inp-icon {
        position: absolute;
        width: 13px;
        height: 15px;
         background: url(~@/assets/img/sp.png) -751px -266px no-repeat;
        left: 21px;
        top: 17px;
        z-index: 9;
        filter: brightness(2);
    }

    .login-inp-icon-pwd {
        position: absolute;
        width: 13px;
        height: 15px;
         background: url(~@/assets/img/sp.png) -810px -266px no-repeat;
        left: 21px;
        top: 17px;
        z-index: 9;
        filter: brightness(2);
    }

    .login-box /deep/ .el-input__inner {
        padding: 0;
        text-indent: 20px;
        padding-left: 22px;
        border-radius: 4px;
        color: #333333;
        border-color: #e1e1e16b;
        height: 53px;
        &:hover{
            border-color: #FFFFFF;
        }
    }
    .login-box /deep/ .el-input__prefix, .el-input__suffix{
        color: #67c23a;
    }

    .login-box /deep/ .test-inp .el-input__inner {
        text-indent: 1px;
    }

    .fileinput-button /deep/ input {
        cursor: pointer;
        position: absolute;
        right: 0px;
        top: 0px;
        opacity: 0;
        visibility: hidden;
        /* -ms-filter: "alpha(opacity=0)"; */
    }

    .fileinput-button /deep/ .el-button {
        cursor: pointer;
        width: 90px !important;
        height: 52px !important;
        color: #666 !important;
    }
</style>
